<template>
  <!-- 管理员 ==> 页面管理（公告内容、积分商品） -->
  <view>
    <!--选项卡： 维修人员信息管理，业主信息管理 -->
    <view>
      <u-subsection :list="xuanXiangList" mode="subsection" :current="subCurrent" @change="xuanXiangChange">
      </u-subsection>
    </view>

    <!-- 小区公告 -->
    <view v-if="subCurrent===0" class="gonggaoBox">
      <!-- title -->
      <view class="gonggao-titleBox">
        <view class="gonggao-title-flag"></view>
        <view class="gonggao-title-text">小区公告</view>
      </view>
      <!-- uni-swipe-action 是最外层包裹性质的容器   滑动删除功能 -->
      <uni-swipe-action>
        <block v-for="(item,index) in noticeList" :key="index">
          <!-- uni-swipe-action-item 可以为其子节点提供滑动操作的效果。需要通过 options 属性来指定操作按钮的配置信息 -->
          <uni-swipe-action-item :right-options="options" @click="swipeActionClickHandler(item)">
            <!-- <navigator :url="'/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id"> -->
            <my-notice :userType="userType" :notice="item"></my-notice>
            <!-- </navigator> -->
          </uni-swipe-action-item>
        </block>
      </uni-swipe-action>
      <view style="margin-bottom: 150rpx;"></view>
      <!-- + -->
      <navigator url="../../subpkg/admin-page-notice-add/admin-page-notice-add">
        <image src="https://www.helloimg.com/images/2022/03/27/ReoTkQ.png" class="notice-add"></image>
      </navigator>
    </view>
    <!-- 积分商城管理 -->
    <view v-else>
      <view>
        <!-- 顶部按钮  新增  编辑  删除  模糊查询-->
        <view style="display: flex;
                    justify-content: space-around;
                    margin-top: 10rpx;">
          <!-- 新增 -->
          <view><button @click="addPeople" type="primary" size="mini">新增</button></view>
          <!-- 编辑 -->
          <view><button @click="editPeople" type="primary" size="mini">编辑</button></view>
          <!-- 删除 -->
          <view><button @click="deletePeople" type="warn" size="mini">删除</button></view>
          <!-- 确认删除 弹框 -->
          <view>
            <u-modal :show="delConfirmshow" :title="title" showCancelButton="true"
              :content="'您确定要删除 <'+ checkedArr[0].name +'> 的信息吗？'" :closeOnClickOverlay="true" @confirm="confirm"
              @cancel="cancel" @close="close1"></u-modal>
          </view>
          <!-- 模糊查询 -->
          <view><button @click="selectPeople" type="primary" size="mini">查询</button></view>
          <!-- 查询弹窗  box  -->
          <view>
            <u-popup :show="showQuery" :overlay="true" :closeOnClickOverlay="true" :closeable="true" :round="10"
              mode="center" @close="close" @open="open">
              <!-- 查询内容box -->
              <view style="width: 100%;" :style="{height: wh + 50 + 'px'}">
                <!-- 整个box -->
                <view class="box" style="margin-top: 150rpx;">
                  <!-- 查询条件信息 -->
                  <view class="box2" style="width: 600rpx;">
                    <view style="font-size: large;font-weight: bold;color: #6A6A6A;">按商品名称模糊查询</view>
                    <view style="border-bottom: 2rpx solid #c1c1c0;">
                      <view class="text" style="width: 150rpx;">关键字：</view>
                      <view class="input"><input type="text" name="nameKey" v-model="nameKey" placeholder="请输入商品名称关键字" /></view>
                      <!-- <view class="input" >
                      </view> -->
                    </view>
                  </view>
                  <view @click="querySubmit" class="submit" style="background-color:#E43D33;margin-top: 200rpx;">查询</view>
                </view>
              </view>
            </u-popup>
          </view>
        </view>
        <!-- 表格 -->
        <view :style="{height: wh + 'px'}">
          <!--zb-table的属性  :pullUpLoading="pullUpLoadingAction" :isShowLoadMore="true" -->
          <zb-table @sort-change="sortChange" ref="zbTable" :summary-method="getSummaries" :highlight="true"
            :show-header="true" :columns="column" :fit="false" row-key="id" @rowClick="rowClick"
            @toggleRowSelection="toggleRowSelection" @toggleAllSelection="toggleAllSelection" :border="true"
            @custom="custom" @edit="buttonEdit" @dele="dele" :data="data"></zb-table>
        </view>
      </view>
      <!-- </uni-card> -->
      <!-- 弹出层box  新增，编辑 -->
      <view>
        <u-popup :show="addeditShow" :overlay="true" :closeOnClickOverlay="true" :closeable="true" :round="10"
          mode="bottom" @close="close" @open="open">
          <!-- 弹出内容box -->
          <view style="width: 100%;" :style="{height: wh + 120 + 'px'}">
            <!-- 整个box -->
            <view class="box">
              <!-- 积分兑换物品信息 -->
              <view class="box2">
                <view style="font-size: large;font-weight: bold;color: #6A6A6A;">积分兑换物品信息</view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">物品名称：</view>
                  <view class="input"><input type="text" name="name" v-model="name" placeholder="请输入物品名称" /></view>
                </view>
                <view>
                  <view class="text">物品图片：</view>
                  <view>
                    <u-upload :fileList="fileList3" @afterRead="afterRead" @delete="deletePic" name="3" multiple
                      :maxCount="1"></u-upload>
                  </view>
                </view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">所需积分：</view>
                  <view class="input"><input type="text" name="price" v-model="price" placeholder="请输入所需积分(数字)" />
                  </view>
                </view>
              </view>
              <view v-if="btnname === '新增'" @click="btnadd" class="submit" style="">新增</view>
              <view v-if="btnname === '编辑'" @click="btnedit" class="submit" style="">保存</view>
            </view>
          </view>
        </u-popup>
      </view>
    </view>



    <!-- 自定义tabBar -->
    <view>
      <u-tabbar :value="tabBarIndex" :fixed="true" @change="tabBarchange" :placeholder="false" activeColor="#1296db"
        :safeAreaInsetBottom="false">
        <block v-for="(item,index) in tabBarList" :key="index">
          <u-tabbar-item :text="item.text">
            <image class="u-page__item__slot-icon" slot="inactive-icon" :src="item.iconPath"></image>
            <image class="u-page__item__slot-icon" slot="active-icon" :src="item.selectedIconPath"></image>
          </u-tabbar-item>
        </block>
      </u-tabbar>
    </view>
  </view>
</template>

<script>
  //获取应用实例
  const app = getApp()
  // 按需导入 mapState ,mapMutations,mapGetters 辅助函数
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'
  export default {
    data() {
      return {
        // 窗口的可用高度 = 屏幕高度 - navigationBar高度 - tabBar 高度
        wh: 0,
        options: [{
          text: '删除', // 显示的文本内容
          style: {
            backgroundColor: '#C00000' // 按钮的背景颜色
          }
        }],
        subCurrent: 0, //0： 公告管理，1: 积分商城管理
        xuanXiangList: ['公告管理', '积分商城管理'],
        noticeList: [],
        // 确认删除弹框
        delConfirmshow: false,
        // 编辑  底部弹出show
        addeditShow: false,
        showQuery:false,//查询弹窗 show
        nameKey:'',//查询 关键字
        btnname: '新增',
        column: [],
        data: [],
        goodsData:[],
        checkedArr: [], //选中的项  数组
        flag1: true,
        flag2: true,
        num: 0,
        num1: 0,
        isShowLoadMore: true,
        // 信息
        name: '', //商品名称
        // imgurl:'',
        fileList3: [], //商品图片
        price: 0, //所需积分
        // 是否正在请求数据    节流阀（防止短时间内重复请求）
        isloading: false
      };
    },
    onLoad(option) {
      this.subCurrent=option.subCurrent
      // 获取公告列表
      this.getNoticeList();
      // 获取积分商品列表
      this.getGoodsList();
      // 获取当前系统的信息
      const sysInfo = uni.getSystemInfoSync()
      // 为 wh 窗口可用高度动态赋值   可用高度 = 屏幕高度 - navigationBar高度 - tabBar高度 - 自定义的search组件高度
      this.wh = sysInfo.windowHeight - 145
      setTimeout(() => {
        this.column = this.goodscolumn;
        this.data = this.goodsData;
      }, 1000)
      
    },
    computed: {
      // 将 m_user 模块中的 userType 数据映射到当前页面中使用
      ...mapState('m_user', ['userType', 'tabBarList1', 'tabBarList2', 'tabBarList3', 'goodscolumn']),
      ...mapState('m_tabbar', ['tabBarList', 'tabBarIndex']),
    },
    methods: {
      // 选择 0： 公告管理 or   1：积分商城管理
      xuanXiangChange(index) {
        this.subCurrent = index;
      },
      // 获取社区公告数据 的方法
      async getNoticeList(cb) {
        // ** 打开节流阀
        this.isloading = true
        const {
          data: res
        } = await uni.$http.get('/notice/getnotice')
        // ** 关闭节流阀
        this.isloading = false
        // 只要数据请求完毕，就立即按需调用 cb 回调函数,cb() 是关闭下拉刷新的
        cb && cb()
        // 请求失败  弹框提醒
        if (res.status !== 200) return uni.$showMsg()
        // 请求成功  为noticeList  赋值
        // 图片url处理
        var tempDataList=res.data;
        for(var i=0;i<tempDataList.length;i++){//循环遍历tempRefuseclassList，对每个tempRefuseclass进行操作
          if(tempDataList[i].img!=null){
            var imgArr=tempDataList[i].img.split(";");//将数据库中的url字符串用；分割为数组
            tempDataList[i].img=[];//重新初始化为数组
            for(var j=0;j<imgArr.length-1;j++){//j<imgArr.length-1  是为了除去最后一个空元素
              tempDataList[i].img[j]=imgArr[j];
            }
          }
        }
        this.noticeList = tempDataList
      },
      async getGoodsList(cb) {
        // ** 打开节流阀
        this.isloading = true
        const {data: res} = await uni.$http.get('/goods/getgoodslist')
        // ** 关闭节流阀
        this.isloading = false
        // 只要数据请求完毕，就立即按需调用 cb 回调函数,cb() 是关闭下拉刷新的
        cb && cb()
        // 请求失败  弹框提醒
        if (res.status !== 200) return uni.$showMsg()
        // 请求成功  为noticeList  赋值
        this.goodsData = res.data
      },
      // 点击了  滑动删除  操作按钮
      async swipeActionClickHandler(notice) {
        notice.img="";
        const {data: res} = await uni.$http.delete('/notice/deletenotice',notice)
         if (res.status !== 200) return uni.$showMsg("删除失败")
         else{
           uni.$showMsg("删除成功")
           setTimeout(()=>{
             uni.redirectTo({
             	url: '/pages/admin-page/admin-page'
             });
           },1000)
         }
        
      },
      
      // 下拉刷新的事件
      onPullDownRefresh() {
        // 1. 重置关键数据
        this.isloading = false;
        this.noticeList = [];
        this.goodsData=[];
        // 2. 重新发起请求   传参（关闭下拉刷新，因为默认不关闭）
        this.getNoticeList(() => uni.stopPullDownRefresh())
        this.getGoodsList(() => uni.stopPullDownRefresh())
      },
      // 表格相关的事件
      sortChange(item, sorterMode, index) {

        console.log('触发排序', item, sorterMode, index)
      },
      cellStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        // console.log('row, column, rowIndex, columnIndex')
        if (columnIndex === 1 || columnIndex === 4) {
          return {
            color: 'red'
          }
        }
      },
      pullUpLoading(done) {
        if (!this.flag1) {
          return
        }
        setTimeout(() => {
          this.data.push({
            date: '2011-05-02',
            name: '王小虎23',
            province: '上海',
            sex: 1,
            price: 33,
            id: 11111 + this.num,
            age: '30',
            city: '普陀区',
            address: '上海市普',
            zip: 200333
          })

          this.num++
          if (this.num === 3) {
            done('ok')
            this.flag1 = false
          } else {
            done()
          }
        }, 2000)
      },

      pullUpLoadingAction(done) {
        console.log(this.flag2)
        if (!this.flag2) {
          return
        }
        setTimeout(() => {
          this.data.push({
            date: '2011-05-02',
            name: '王小虎23',
            province: '上海',
            sex: 1,
            price: 33,
            id: "11111",
            age: '30',
            city: '普陀区',
            address: '上海市普',
            zip: 200333
          })

          this.num1++
          if (this.num1 === 3) {
            this.$refs.zbTable.pullUpCompleteLoading('ok')
            this.flag2 = false
          } else {
            this.$refs.zbTable.pullUpCompleteLoading()
          }
        }, 1000)
      },
      buttonEdit(ite, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击编辑'
        })
        console.log(ite, index)
      },
      dele(ite, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击删除'
        })
        // alert('点击删除')
        console.log(ite, index)
      },
      custom() {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击自定义'
        })
      },
      toggleAllSelection(checked, arr) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击全选'
        })
        console.log('全选', checked, arr)
        this.checkedArr = arr;
      },
      toggleRowSelection(checked, arr) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击单选'
        })
        console.log('单选', checked, arr)
        this.checkedArr = arr;
      },
      currentChange(row, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '选中当前一行'
        })
        console.log('单选', row, index)
      },
      rowClick(row, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '单击某行'
        })
        console.log('单击某行', row, index)
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          if (column.name === 'price') {
            const values = data.map(item => Number(item[column.name]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              sums[index] += ' 元';
            }
          } else {
            sums[index] = 'N/A';
          }
        });
        return sums;
      },
      // 新增
      addPeople() {
        this.btnname = '新增';
        this.addeditShow = true;
      },
      // 编辑
      editPeople() {
        if (this.checkedArr.length !== 1) {
          uni.$showMsg("只能选中一项进行编辑！");
        } else {
          this.btnname = '编辑';
          this.name = this.checkedArr[0].name;
          // user.img=this.fileList3[0];
          // user.img = '',
          var imgurl = {};
          imgurl.url = this.checkedArr[0].img;
          this.fileList3[0] = imgurl;
          this.price = this.checkedArr[0].price;
          this.addeditShow = true;
        }
      },
      // 删除
      deletePeople() {
        if (this.checkedArr.length < 1) {
          uni.$showMsg("至少选中一项进行删除！");
        } else {
          this.delConfirmshow = true;
        }

      },
      // 确认删除弹框  确认按钮单击事件
      async confirm() {
        const {data: res} = await uni.$http.delete('/goods/deletegoods',this.checkedArr)
         if (res.status !== 200) return uni.$showMsg("删除失败")
         else{
           uni.$showMsg("删除成功")
           setTimeout(()=>{
             uni.redirectTo({
             	url: '/pages/admin-page/admin-page?subCurrent=1'
             });
           },1000)
           this.checkedArr.pop();
           this.delConfirmshow = false;
           console.log("删除成功")
         }
      },
      // 确认删除弹框  取消按钮单击事件
      cancel() {
        this.delConfirmshow = false;
      },
      // 确认删除弹框  关闭按钮单击事件
      close1() {
        this.delConfirmshow = false;
        this.showQuery=false;
      },
      // 查询
      selectPeople() {
        this.showQuery=true;
      },
      // 弹出层 btn新增
      async btnadd() {
        if(this.name==='' || this.price==='' || this.fileList3.length===0){
          return uni.$showMsg("商品名、所需积分、图片不能为空！")
        }
        var goods = {};
        // goods.id=   数据库里面是自增字段，存入数据库时，这个设置为  null 即可
        goods.name = this.name;
        goods.img=this.fileList3[0].url;
        goods.checked = false;
        goods.price = this.price;
        const {data: res} = await uni.$http.put('/goods/addgoods', goods)
        if (res.status !== 200) return uni.$showMsg("新增失败")
        else {
          uni.$showMsg("新增成功")
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/admin-page/admin-page?subCurrent=1'
            });
          }, 1000)
        }
        // this.data.push(goods);
        this.close();
      },
      // 弹出层 btn保存
      async btnedit() {
        var goods = {};
        goods.id = this.checkedArr[0].id;
        goods.name = this.name;
        goods.img = this.fileList3[0].url;
        goods.checked = false;
        goods.price = this.price;
        const {data: res} = await uni.$http.post('/goods/updategoods', goods)
        if (res.status !== 200) return uni.$showMsg("修改失败")
        else {
          uni.$showMsg("修改成功")
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/admin-page/admin-page?subCurrent=1'
            });
          }, 1000)
          this.checkedArr.pop();
          this.close();
        }
      },
      //弹窗  查询按钮
      async querySubmit(){
        let nameKey = this.nameKey;
        console.log("querySubmit==========>>>>>>>nameKey")
        console.log(nameKey);
        const {data: res} = await uni.$http.get('/goods/getGoodsLikeName',{"nameKey":nameKey})
        if (res.status !== 200) return uni.$showMsg()
        this.data=res.data;
        this.showQuery=false;
      },
      radioChange(e) {
        this.sex = e.detail.value;
      },
      // 底部弹出的新增，编辑   打开事件
      open() {
        // console.log('open');
      },
      // 底部弹出的新增，编辑   关闭事件
      close() {
        this.addeditShow = false
        this.name = '';
        this.sex = '';
        this.age = 0;
        // user.img=this.fileList3[0];
        // user.img = '',
        this.address = '';
        this.username = '';
        this.password = '';
        this.status = '';
        this.fileList3=[];
        this.showQuery=false;
      },
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },
      // 新增图片
      async afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        console.log(event.name)
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))
          fileListLen++
        }
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: app.globalData.baseUrl+'/qiniu/testUpload', // Spring Boot接口地址
            filePath: url,
            name: 'file',
            formData: {
              user: 'test'
            },
            success: (res) => {
              setTimeout(() => {
                resolve(res.data)
              }, 1000)
            }
          });
        })
      },
      // 自定义tabBar
      ...mapMutations('m_tabbar', ['updateTabBarList', 'updateTabBarIndex']),
      tabBarchange(name) {
        // uni.switchTab({
        //   url: this.tabBarList[name].pagePath
        // })
        uni.redirectTo({
          url: this.tabBarList[name].pagePath
        })
        this.setTabBarIndex(name);
      },
      setTabBarIndex(index) {
        this.updateTabBarIndex(index);
      }
    }
  }
</script>

<style lang="scss">
  // 公告Box
  .gonggaoBox {
    margin-left: 0rpx;
    margin-top: 30rpx;
    width: 750rpx;
    // height: 1180rpx;
  }

  .gonggao-titleBox {
    border-radius: 15rpx;
    background-color: #f2f1ec;
  }

  .gonggao-title-flag {
    margin-left: 30rpx;
    margin-top: 5rpx;
    float: left;
    width: 15rpx;
    height: 50rpx;
    background-color: #1296db;
  }

  .gonggao-title-text {
    padding-top: 5rpx;
    margin-left: 60rpx;
    font-weight: bold;
    font-size: 42rpx;
    width: 670rpx;
    height: 60rpx;
  }

  .notice-add {
    width: 120rpx;
    height: 120rpx;
    position: fixed;
    bottom: 150rpx;
    right: 30rpx;
    z-index: 9999;
  }

  .box {
    padding: 30rpx;
  }

  .box1,
  .box2 {
    // border-radius: 30rpx;
    margin-bottom: 30rpx;
    padding: 25rpx;
    box-shadow: 0 0 15rpx #999999
  }

  .box1>view,
  .box2>view {
    padding: 10rpx;
    display: flex;
    margin-bottom: 10rpx;
    font-family: Microsoft YaHei;

    color: #333333;
  }

  .text {
    width: 30%;
    text-align: left;
    overflow: auto;
  }


  .submit {
    background-color: #1599FD;
    color: #FFFFFF;
    font-weight: bold;
    text-align: center;
    border-radius: 15rpx;
    line-height: 100rpx;
    height: 100rpx;
  }


  .u-page {
    padding: 0;

    &__item {

      &__title {
        color: $u-tips-color;
        background-color: $u-bg-color;
        padding: 30rpx;
        font-size: 30rpx;

        &__slot-title {
          color: $u-primary;
          font-size: 30rpx;
        }
      }

      &__slot-icon {
        width: 70rpx;
        height: 70rpx;
      }
    }
  }
</style>
